import React, { useState, useEffect, useContext } from "react";
import { useNavigate, Link } from "react-router-dom";
import { AppState } from "../App";
import { ethers } from "ethers";
import { useParams } from "react-router-dom";
import "../css/forus.css";
import "../css/loader.css";

function ForUs() {
  const App = useContext(AppState);
  const { id } = useParams();
  const [Useramount, setUseramount] = useState();
  const [Data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const image =
    "https://images.pexels.com/photos/464342/pexels-photo-464342.jpeg";

  const [showOngoing, setShowOngoing] = useState(true);

  const CreateRecord = async () => {
    navigate("/header/creatforus");
  };

  //获取截止时间
  const calculateRemainingTime = (endTime) => {
    const now = new Date().getTime();
    const end = endTime * 1000;
    const distance = end - now;
    if (distance < 0) {
      return "已结束";
    }
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor(
      (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    );
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
    return `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
  };

  //获取当前创建时间
  const calculateCreatTime = (currentTime) => {
    const date = new Date(currentTime * 1000);

    const years = date.getFullYear();
    const months = date.getMonth() + 1; //0-11：1-12月
    const days = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();

    return `${years}年 ${months}月 ${days}日 ${hours}点 ${minutes}分${seconds}秒`;
  };

  useEffect(() => {
    if (App.Foundationcontract) {
      const getProposals = async () => {
        try {
          const Count = await App.Foundationcontract.userrequestsNumber();

          let proposals = [];
          for (let i = 0; i < Count; i++) {
            const Proposal = await App.Foundationcontract.userrequestions(i);
            const updatedProposal = {
              ...Proposal,
              remainingTime: calculateRemainingTime(Proposal.endTime),
            };
            if (showOngoing && updatedProposal.remainingTime !== "已结束") {
              proposals.push(updatedProposal);
            } else if (
              !showOngoing &&
              updatedProposal.remainingTime === "已结束"
            ) {
              proposals.push(updatedProposal);
            }
          }
          // console.log(proposals.currentTime)
          const shuffledProposals = proposals.sort(
            (a, b) => Number(b.currentTime) - Number(a.currentTime)
          );
          setData(shuffledProposals);
          setLoading(false);
        } catch (error) {
          console.log(error);
        }
      };
      getProposals();
    }
  }, [App.Foundationcontract, showOngoing]);

  const Contribute = async (id, Useramount) => {
    try {
      const tx = await App.Foundationcontract.usersendMoney(id, {
        value: Useramount,
      });
      const transactionHash = tx.hash;
      await tx.wait();
      alert(`捐赠成功!请您保存交易哈希:${transactionHash}`);
      window.location.reload();
    } catch (error) {
      console.log(error.message);
      alert("捐款必须大于100WEI");
    }
  };

  const itemsPerPage = 3; //每页显示三个
  const [currentPage, setCurrentPage] = useState(1);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = Data.slice(indexOfFirstItem, indexOfLastItem);
  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(Data.length / itemsPerPage); i++) {
    pageNumbers.push(i);
  }

  const handleClick = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  useEffect(() => {
    const interval = setInterval(() => {
      setData((prevData) =>
        prevData.map((item) => {
          return {
            ...item,
            remainingTime: calculateRemainingTime(item.endTime),
            creatTime: calculateCreatTime(item.currentTime),
          };
        })
      );
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      {loading && <div className="loader"></div>}
      <div
        className="flex flex-col justify-center items-center h-screen"
        style={{
          backgroundImage: `url(${image})`,
          backgroundColor: "rgb(10, 10, 10)",
          backgroundSize: "cover",
          backgroundPosition: "center",
          width: "100%",
          height: "100vh",
        }}
      >
        <div className="oneDiv">
          <div className="content_container">
            <span className="contentFont text-black text-6xl font-bold contentSpan">
              为我们筹款
            </span>
          </div>
          <div
            onClick={CreateRecord}
            className="flex border-opacity-60 bg-opacity-90 text-lg font-medium border-2  cursor-pointer text-black mt-1 rounded-2xl justify-center items-center py-1 px-2 mt-4 connectDiv"
          >
            创建筹款
          </div>
        </div>
      </div>

      <p className="text-center text-black text-3xl font-bold mt-10 mb-10">
        无论是举办生日派对、规划社区项目、参加挑战还是跑马拉松，
        <br />
        您都可以创建个人筹款页面来庆祝——同时与我们脆弱的野生动植
        <br />
        物、栖息地和自然资源分享您的爱心。现在就开始创建您的页面吧！
      </p>
      <div className="toggle-container">
        <button
          onClick={() => setShowOngoing(true)}
          className={`toggle-button ${showOngoing ? "active" : ""}`}
        >
          正在进行
        </button>
        <button
          onClick={() => setShowOngoing(false)}
          className={`toggle-button ${!showOngoing ? "active" : ""}`}
        >
          已结束
        </button>
      </div>
      <div className="divFFF">
        <div class="grid sm:grid-cols-2 lg:grid-cols-3 gap-2">
          {currentItems.length !== 0 ? (
            currentItems.map((e, id) => {
              return (
                <div class="p-4" key={id}>
                  <div class="h-full bg-gray-100 bg-opacity-75 px-8 pt-16 pb-24 rounded-lg overflow-hidden text-center relative dynamic-background">
                    <h2 class="tracking-widest -ml-5 text-15px title-font font-medium text-gray-900 mb-1">
                      筹款方地址
                    </h2>
                    <h2
                      class="tracking-widest -ml-5 text-base title-font font-medium text-gray-900 mb-1"
                      style={{ fontSize: "11px" }}
                    >
                      {e.recipient}
                    </h2>
                    <h2 class="tracking-widest -ml-5 text-base title-font font-medium text-gray-900 mb-1">
                      {e.tittle}
                    </h2>
                    <Link
                      to={`/header/forus/${e.uniqueid}`}
                      className="image-link"
                    >
                      <img
                        style={{ width: "300px", height: "300px" }}
                        src={`https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${e.photo}`}
                        alt="Proposal Photo"
                        className="hover-image"
                      />
                    </Link>
                    <p
                      className="leading-relaxed mt-2 mb-2 "
                      style={{ fontSize: "29px" }}
                    >
                      {e.description}
                    </p>
                    <p className="mb-2 remainTime">
                      截至时间--{e.remainingTime}
                    </p>
                    <p className="mb-5 currentTime">创建时间--{e.creatTime}</p>
                    <div class="text-center mt-2 leading-none flex justify-center absolute bottom-0 left-0 w-full py-4">
                      <span class="text-black  font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                        已收到
                      </span>
                      <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                        {e.userraisedAmount.toString()} WEI {}
                      </span>
                      <span class="text-black ml-10 font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                        所需金额
                      </span>
                      <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                        {Number(e.targetMoney.toString())} WEI {}
                      </span>
                    </div>
                    {showOngoing && (
                      <div className="flex justify-center absolute bottom-10 left-0 w-full py-4">
                        <input
                          type="text"
                          placeholder="捐款金额"
                          className="donateInput"
                          onChange={(e) => setUseramount(e.target.value)}
                        />
                        <button
                          onClick={() =>
                            Contribute(
                              e.uniqueid,
                              ethers.utils.parseUnits(Useramount, 0)
                            )
                          }
                          className=" flex mx-auto mt-10 text-white bg-yellow-400 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded"
                        >
                          捐赠
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              );
            })
          ) : (
            <div className="flex items-center justify-center nonDIv">
              <div className="title-font sm:text-2xl text-xl font-medium text-gray-900  text-black">
                没有相关内容。
              </div>
            </div>
          )}
        </div>
      </div>
      {currentItems.length !== 0 && (
        <div className="pagination-container">
          <button
            className={`pagination-button ${
              currentPage === 1 ? "disabled" : ""
            }`}
            onClick={() => handleClick(currentPage - 1)}
            disabled={currentPage === 1}
          >
            上一页
          </button>
          {pageNumbers.map((number) => (
            <button
              key={number}
              className={`pagination-button ${
                currentPage === number ? "active" : ""
              }`}
              onClick={() => handleClick(number)}
            >
              {number}
            </button>
          ))}
          <button
            className={`pagination-button ${
              currentPage === pageNumbers.length ? "disabled" : ""
            }`}
            onClick={() => handleClick(currentPage + 1)}
            disabled={currentPage === pageNumbers.length}
          >
            下一页
          </button>
        </div>
      )}
      <footer className="footer">
        <div className="footer-container">
          <div className="footer-links">
            <div className="link-wrapper">
              <a className="footer-link" href="#">
                关于我们
              </a>
              <div className="tooltip">请进入官方网址查看详情</div>
            </div>
            <div className="link-wrapper">
              <a className="footer-link" href="#">
                联系我们
              </a>
              <div className="tooltip">
                电话号码:123-456-7890
                <br />
                QQ邮箱号:12345678
              </div>
            </div>
            <div className="link-wrapper">
              <a className="footer-link" href="#">
                合作
              </a>
              <div className="tooltip">请致电123-456-7890</div>
            </div>
          </div>
          <div className="footer-copyright">
            <p>
              &copy; {new Date().getFullYear()} SongWarm. 以你之名 爱这个世界.
            </p>
          </div>
        </div>
      </footer>
    </div>
  );
}

export default ForUs;
